package com.czh.servlet.User;

import com.alibaba.fastjson.JSONArray;
import com.czh.pojo.Role;
import com.czh.pojo.User;
import com.czh.service.Role.RoleServiceImpI;
import com.czh.service.User.UserService;
import com.czh.service.User.UserServiceImpl;
import com.czh.util.Constants;
import com.czh.util.PageSupport;
import com.mysql.cj.util.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        String method = req.getParameter("method");
        if ("savepwd".equals(method)) {
            this.upDatePwd(req, resp);
        } else if ("pwdmodify".equals(method)) {
            checkOldPwd(req, resp);
        } else if ("query".equals(method)) {
            query(req, resp);
        } else if ("add".equals(method)) {
            addUser(req, resp);
        } else if ("getrolelist".equals(method)) {
            getRoleList(req,resp);
        } else if ("ucexist".equals(method)) {
            userCodeExist(req, resp);
        } else if ("view".equals(method)) {
            userView(req,resp);
        }else if("deluser".equals(method)){
            userDelete(req,resp);
        } else if ("modify".equals(method)) {
            ModifyView(req,resp);
        } else if ("modifyexe".equals(method)) {
            Modify(req,resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        doGet(req, resp);
    }
    protected void upDatePwd(HttpServletRequest req, HttpServletResponse resp) {
        Object obj = req.getSession().getAttribute(Constants.USER_SESSION);//获取session中的user对象
        String newPassword = req.getParameter("newpassword");
        boolean flag;
        if (obj == null || StringUtils.isNullOrEmpty(newPassword)) {
            req.setAttribute("message", "旧密码不能为空!");
        } else {
            UserService userService = new UserServiceImpl();
            flag = userService.UpdatePsd(((User) obj).getId(), newPassword);//获取用户的密码
            if (flag) {
                req.setAttribute("message", "密码更改成功!请重新登录!");
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute("message", "密码更改失败!");
            }
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    protected void checkOldPwd(HttpServletRequest req, HttpServletResponse resp) {
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能的Map：结果集
        Map<String, String> resultMap = new HashMap<>();

        if (o == null) {//Session失效
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {//输入的密码为空
            resultMap.put("result", "error");
        } else {
            String userPassword = ((User)o).getUserPassword();
            if (oldpassword.equals(userPassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");//旧密码错误
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray 阿里巴巴的JSON工具类，转换格式。
            /*
            resultMap = ["reslut","sessionerror","reslut","error"]
            Json格式 = {key:value}
             */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void query(HttpServletRequest req, HttpServletResponse resp)  {
        //从前端获取数据：
        String queryname = req.getParameter("queryname");
        String queryUserRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        //初值
        int userPageNo = 1;
        int userRole = 0;
        int pageSize = 5;
        //输入了检索项就赋值
        if (queryUserRole != null && queryUserRole.length() > 0) {
            userRole = Integer.parseInt(queryUserRole);
        }
        if (pageIndex != null && pageIndex.length() > 0) {
            userPageNo = Integer.parseInt(pageIndex);
        }
        //将数据存入工具类,算出总页数
        UserServiceImpl userService = new UserServiceImpl();
        int userCount = userService.userCount(queryname, userRole);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setCurrentPageNo(userPageNo);
        pageSupport.setTotalCount(userCount);
        int totalPageCount = pageSupport.getTotalPageCount();
        //页码跳转判断
        if (userPageNo < 0) {
            userPageNo = 1;
        } else if (userPageNo > totalPageCount) {
            userPageNo = totalPageCount;
        }
        //获取身份列表
        RoleServiceImpI roleServiceImpI = new RoleServiceImpI();
        List<Role> roleList;
        try {
            roleList = roleServiceImpI.getRoleList();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //用户表
        List<User> userList = new UserServiceImpl().userList(queryname, userRole, userPageNo, pageSize);
        //将数据传入前端
        req.setAttribute("roleList", roleList);
        req.setAttribute("userList", userList);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("totalCount", userCount);
        req.setAttribute("currentPageNo", userPageNo);
        req.setAttribute("queryUserRole", userRole);
        req.setAttribute("queryUserName", queryname);

        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            throw new RuntimeException(e);
        }
    }
    protected void addUser(HttpServletRequest req, HttpServletResponse resp) {
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));//把字符串变成日期。
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        UserService userService = new UserServiceImpl();
        try {
            if (userService.userAdd(user)) {
                resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
            } else {
                req.getRequestDispatcher("useradd.jsp").forward(req, resp);
            }
        }catch (Exception e){
            throw new RuntimeException("系统异常！");
        }
    }
    protected void getRoleList(HttpServletRequest req,HttpServletResponse resp){
        try {
            List<Role> roleList= (new RoleServiceImpI()).getRoleList();
            PrintWriter printWriter = resp.getWriter();
            resp.setContentType("application/json");
            printWriter.write(JSONArray.toJSONString(roleList));
            printWriter.flush();
            printWriter.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    protected void userCodeExist(HttpServletRequest req,HttpServletResponse resp){
        String userCode = req.getParameter("userCode");
        User user = new UserServiceImpl().userCodeSelect(userCode);
        Map<String, String> result = new HashMap<>();
        if(StringUtils.isNullOrEmpty(userCode)){
            result.put("userCode","exist");
        }else {
            if(user==null){
                result.put("userCode","no");
            }else {
                result.put("userCode","exist");
            }
        }
        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(result));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    protected  void userView(HttpServletRequest req,HttpServletResponse resp){
        String id = (req.getParameter("uid"));
        if(!StringUtils.isNullOrEmpty(id)) {
            User user = new UserServiceImpl().userIdSelect(Integer.valueOf(id));
            req.setAttribute("user", user);
            try {
                req.getRequestDispatcher("userview.jsp").forward(req, resp);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    protected void userDelete(HttpServletRequest req,HttpServletResponse resp){
        int delId = Integer.parseInt(req.getParameter("uid"));
        HashMap<String, String> resultMap = new HashMap<>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            UserService userService = new UserServiceImpl();
            try {
                if (userService.userDelete_id(delId)) {
                    resultMap.put("delResult", "true");
                } else {
                    resultMap.put("delResult", "false");
                }
            } catch (SQLException e) {
                throw new RuntimeException("servlet层userDelete出错!");
            }
            try {
                resp.setContentType("application/json");
                PrintWriter writer = resp.getWriter();
                writer.write(JSONArray.toJSONString(resultMap));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    protected void ModifyView(HttpServletRequest req,HttpServletResponse resp){
        String id = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(id)) {
            //调用后台方法得到user对象
            try {
                User user = new UserServiceImpl().userIdSelect(Integer.valueOf(id));
                req.setAttribute("user",user);
                req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    protected void Modify(HttpServletRequest req,HttpServletResponse resp){
        String id = req.getParameter("uid");
        String gender = req.getParameter("gender");
        String userName = req.getParameter("userName");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        boolean modify = new UserServiceImpl().modify(user);
        try {
            if (modify) {
                resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
            } else {
                req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
            }
        }catch (Exception e){
            throw new RuntimeException("servlet层modify出错!");
        }

    }
}


